# coding:utf-8
from PySide6 import QtCore
from PySide6.QtCore import Slot, QTimer, Signal
from PySide6.QtWidgets import QWidget
import serial.tools.list_ports_windows #windows 下

from APP.UltrasonicDetectionModule.UI.UltrasonicDetectionModule import Ui_UltrasonicDetectionModule
from APP.UltrasonicDetectionModule.SendData.SendDetectionModuleData import SendDetectionModuleCode
from APP.UltrasonicDetectionModule.Handle.serialUltrasonicDetectionModulehandle import SerialUltrasonicDetectionModuleHandle
from qfluentwidgets import TeachingTip, TeachingTipTailPosition, InfoBarIcon

from Util.util import HexToStrOnTime, BytesToStrOnTime

class FocusInterface_UltrasonicDetectionModule(QWidget, Ui_UltrasonicDetectionModule):

    def __init__(self, parent=None):
        super().__init__(parent=parent)
        self.setupUi(self)

        plist = list(serial.tools.list_ports_windows.comports())  # Window下
        # plist = glob.glob('/dev/tty[A-Za-z]*')  #Linux下
        self.m_SerialsComboList = []
        self.m_SerialComList = []
        if len(plist) <= 0:
            # print(u'没有发现端口！')
            pass
        else:
            for plist1 in plist:                            #Windows
                plist2 = list(plist1)                       #Windows
                self.m_SerialComList.append(plist2[0])      #Windows
                self.m_SerialsComboList.append(plist2[1])   #Windows
            # self.m_SerialsComboList = plist[0]            #Linux

        self.SerialComboBox.addItems(self.m_SerialsComboList)
        self.serialHandle = SerialUltrasonicDetectionModuleHandle()
        self.serialHandle.EventDetectionModule.connect(self.EventSlot)  # type: ignore
        self.SerialOpenBtn.clicked.connect(self.OnOpenComPressed)  # type: ignore
        self.ClearTxBtn.clicked.connect(self.OnClearTxData)  # type: ignore
        self.ClearRxBtn.clicked.connect(self.OnClearRxData)  # type: ignore
        self.serialHandle.DetectionModuleReceiveDataSignal.connect(self.DataReceiveSlot)  # type: ignore
        self.SigleSendBtn.clicked.connect(self.SendData)  # type: ignore

        self.AllRadioBtn.clicked.connect(self.AllorSignel) # type: ignore
        self.No1RadioBtn.clicked.connect(self.AllorSignel)  # type: ignore
        self.No2RadioBtn.clicked.connect(self.AllorSignel)  # type: ignore
        self.No3RadioBtn.clicked.connect(self.AllorSignel)  # type: ignore
        self.No4RadioBtn.clicked.connect(self.AllorSignel)  # type: ignore

        self.timer = QTimer(self)
        self.timer.timeout.connect(self.SendData)
        self.CycleSendSBtn.checkedChanged.connect(self.AutoSend)

    @Slot(bool)
    def EventSlot(self, message):
        if message:
            self.SerialOpenBtn.setText(u'关闭串口')
        else:
            self.SerialOpenBtn.setText(u'打开串口')
        pass

    @Slot()
    def OnOpenComPressed(self):
        if not self.serialHandle.openSerialPort(self.m_SerialComList[self.SerialComboBox.currentIndex()]):
            self.showBottomTip(self.SerialOpenBtn, u'当前端口已被占用，或存在问题，无法打开！')
        pass

    @Slot()
    def OnClearTxData(self):
        self.TxDataTextEdit.clear()
        pass

    @Slot()
    def OnClearRxData(self):
        self.RxDataTextEdit.clear()
        pass

    @Slot(list)
    def DataReceiveSlot(self, message):
        if self.AllRadioBtn.isChecked():
            No1Distance = (message[4]*256 + message[5]) / 1000.0
            No2Distance = (message[6]*256 + message[7]) / 1000.0
            No3Distance = (message[8] * 256 + message[9]) / 1000.0
            No4Distance = (message[10] * 256 + message[11]) / 1000.0
            self.No1DistanceLabel.setText(u'通道1距离：' + format(No1Distance, ".3f") + u'm')
            self.No2DistanceLabel.setText(u'通道2距离：' + format(No2Distance, ".3f") + u'm')
            self.No3DistanceLabel.setText(u'通道3距离：' + format(No3Distance, ".3f") + u'm')
            self.No4DistanceLabel.setText(u'通道4距离：' + format(No4Distance, ".3f") + u'm')
        elif self.No1RadioBtn.isChecked():
            No1Distance = (message[4] * 256 + message[5]) / 1000.0
            self.No1DistanceLabel.setText(u'通道1距离：' + format(No1Distance, ".3f") + u'm')
            self.No2DistanceLabel.setText(u'通道2距离：' + u'NONE')
            self.No3DistanceLabel.setText(u'通道3距离：' + u'NONE')
            self.No4DistanceLabel.setText(u'通道4距离：' + u'NONE')
        elif self.No2RadioBtn.isChecked():
            No2Distance = (message[4] * 256 + message[5]) / 1000.0
            self.No1DistanceLabel.setText(u'通道1距离：' + u'NONE')
            self.No2DistanceLabel.setText(u'通道2距离：' + format(No2Distance, ".3f") + u'm')
            self.No3DistanceLabel.setText(u'通道3距离：' + u'NONE')
            self.No4DistanceLabel.setText(u'通道4距离：' + u'NONE')
        elif self.No3RadioBtn.isChecked():
            No3Distance = (message[4] * 256 + message[5]) / 1000.0
            self.No1DistanceLabel.setText(u'通道1距离：' + u'NONE')
            self.No2DistanceLabel.setText(u'通道2距离：' + u'NONE')
            self.No3DistanceLabel.setText(u'通道3距离：' + format(No3Distance, ".3f") + u'm')
            self.No4DistanceLabel.setText(u'通道4距离：' + u'NONE')
        elif self.No4RadioBtn.isChecked():
            No4Distance = (message[4] * 256 + message[5]) / 1000.0
            self.No1DistanceLabel.setText(u'通道1距离：' + u'NONE')
            self.No2DistanceLabel.setText(u'通道2距离：' + u'NONE')
            self.No3DistanceLabel.setText(u'通道3距离：' + u'NONE')
            self.No4DistanceLabel.setText(u'通道4距离：' + format(No4Distance, ".3f") + u'm')
        self.RxDataTextEdit.appendPlainText(HexToStrOnTime(message).upper())
        pass

    @Slot()
    def SendData(self):
        code = 0x01
        if self.AllRadioBtn.isChecked():
            code = 0x01
        if self.No1RadioBtn.isChecked():
            code = 0x10
        if self.No2RadioBtn.isChecked():
            code = 0x11
        if self.No3RadioBtn.isChecked():
            code = 0x12
        if self.No4RadioBtn.isChecked():
            code = 0x13
        TxDataBuffer = SendDetectionModuleCode(0x01, code)
        self.serialHandle.SendFrame(TxDataBuffer)
        self.TxDataTextEdit.appendPlainText(BytesToStrOnTime(TxDataBuffer).upper())

    @Slot()
    def AutoSend(self):
        if self.CycleSendSBtn.isChecked():
            self.timer.start(250)
            pass
        else:
            self.timer.stop()
            pass
        pass

    @Slot()
    def AllorSignel(self):
        if self.AllRadioBtn.isChecked():
            self.serialHandle.setAllorSignel(True)
        else:
            self.serialHandle.setAllorSignel(False)

    def showBottomTip(self, Target, message):
        TeachingTip.create(
            target=Target,
            icon=InfoBarIcon.ERROR,
            title='提示：',
            content=message,
            isClosable=True,
            tailPosition=TeachingTipTailPosition.TOP,
            duration=2000,
            parent=self
        )

    def closeEvent(self, a0):
        self.timer.stop()
        self.serialHandle.closeSerialPort()
        pass